<?php
//$Id: user.php 331 2012-04-29 10:45:50Z tomqin@gmail.com $

/**
 * User 用户类
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

define('USER_DISABLED', -1);
define('USER_GUEST',    0);
define('USER_UNVERIFY', 0);
define('USER_NORMAL',   1);
define('USER_BUSINESS', 2);
define('USER_ADMIN',    9);

class User{
    var $sid;
    var $uid;
    var $name;
    var $email;
    var $status = 0; //-1=禁用；0=游客/未验证的用户；1=普通；2=企业账户；9=超级管理员
    var $login_dt;
    var $login_ip;
    var $admin_city = array();
    var $admin_shop = array();
    var $last_active = 0; //上次活动时间

    private function __construct(){

    }

    function isLogin(){
        return $this->uid && $this->status > 0;
    }

    function getTitle(){
        switch($this->status){
            case USER_DISABLED: return '禁用';
            case USER_GUEST:    return '游客';
            case USER_UNVERIFY: return '游客';
            case USER_NORMAL:   return '普通用户';
            case USER_BUSINESS: return '企业账户';
            case USER_ADMIN:    return '超级管理员';
            default:            return '无效用户';
        }
    }

    static function getInstance(){
        static $userObj = null;
        if(!$userObj){
            $user = self::getUser();
            $userObj = new User();
            if($user['uid'] > 0){
                $userObj->sid    = $user['sid'];
                $userObj->uid    = $user['uid'];
                $userObj->name   = $user['name'];
                $userObj->email  = $user['email'];
                $userObj->status = $user['status'];
                $userObj->login_dt   = $user['login_dt'];
                $userObj->login_ip   = $user['login_ip'];
                $userObj->admin_city = $user['admin_city'];
                $userObj->admin_shop = $user['admin_shop'];
            }else{
                $userObj->sid    = $user['sid'];
                $userObj->uid    = 0;
                $userObj->name   = 'Guest';
                $userObj->status = 0;
            }
        }
        return $userObj;
    }

    private static $cookie = array(
        'sid' => '',
        'uid' => 0,
        'name' => 'Guest',
        'expire' => 0,
    );

    static function initUserCookie(){
        $guest = false;
        $auth  = App::getCookie('auth');
        if(empty($auth)){
            $guest = true;
        }else{
            @list($sid, $uid, $name, $expire) = explode(';', $auth);
            $sid = trim($sid);
            $uid = intval($uid);
            $name = trim($name);
            $expire = trim($expire);

            if($guest || !$uid || !preg_match('/[\d\w]{6}/i', $sid)){
                $guest = true;
            }
        }
        if($guest){
            $sid = empty($sid) ? randomstr(6) : $sid;
            self::$cookie = array('sid' => $sid, 'uid' => 0, 'name' => 'Guest', 'expire' => 60);
            if(empty($auth)){
                App::setCookie('auth', join(';', self::$cookie), self::$cookie['expire']);
            }
        }else{
            self::$cookie = array('sid' => $sid, 'uid' => $uid, 'name' => $name, 'expire' => $expire);
        }
    }

    static function getUser($detail = false){
        self::initUserCookie();
        extract(self::$cookie);

        $user = null;
        if($sid && $uid && $expire){
            $user = Db::getRow("SELECT * FROM `biz_user` u LEFT JOIN `biz_session` s ON s.uid = u.uid WHERE s.uid = '{$uid}' AND s.sid = '{$sid}'");
            if($user){
                if(TIMESTAMP - $user['stime'] > $expire*30){ //经历一半时间，更新设置
                    Db::update('biz_session', array('stime' => TIMESTAMP), "uid = '{$uid}' AND sid = '{$sid}'");
                    App::updateCookie('auth', $expire);
                }
            }
        }

        if($user){
            return $user;
        }else{
            return self::$cookie; //Guest
        }
    }

    static function setUser($uid = 0, $name = 'Guest', $expire = 60){
        if(empty(self::$cookie['sid'])){
            self::initUserCookie();
        }
        $sid  = self::$cookie['sid'];
        $uid  = intval($uid);
        $name = trim($name);

        if($uid){
            //更新Session
            $session = array(
                'sid'  => $sid,
                'uid'  => $uid,
                'name' => $name,
                'stime'=> TIMESTAMP,
            );
            Db::insert('biz_session', $session, true);
        }else{
            $uid  = 0;
            $name = 'Guest';
        }

        //更新Cookie
        self::$cookie['uid'] = $uid;
        self::$cookie['name'] = $name;
        self::$cookie['expire'] = $expire;

        App::setCookie('auth', join(';', self::$cookie), $expire);
    }

    //expire 过期时间（分钟）
    static function login($name, $pwd, $expire = 30){
        $name = Db::escapeString($name);
        $pwd  = (strlen($pwd) == 32) ? $pwd : md5($pwd);
        $user = DB::getRow("select * from `biz_user` where `name` like '{$name}'");
        if($user['uid'] && $user['pwd'] == md5($user['salt'].$pwd)){
            self::setUser($user['uid'], $user['name'], $expire);
            return true;
        }else{
            self::setUser(0);
            return false;
        }
    }
}

?>